// 搜索模块路由处理函数

const server = require("../server/search")
const utils = require("../common/utils")
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥

// 根据email搜索用户
exports.getUserByEmail = (req, res) => {
  let { email } = req.body
  let token = req.get('Authorization').split(' ')[1]
  // 自己的id
  let id = jwt.verify(token, secretKey).id
  // 是否好友
  server.isFriend(id, email).then(isFriend => {
    // 获取用户信息
    server.getFriendInfo(email).then(result => {
     if (result.hasOwnProperty('register_time')) {
       result.register_time = utils.formatDate(new Date(result.register_time).getTime())
       result.isFriend = isFriend
     }
     return res.send({
       code: 200,
       message: "获取用户信息成功",
       data: result
     })
    }).catch(e => {
      return res.cc(e)
    })
  }).catch(e => {
    return res.cc(e)
  })
}

// 根据id获取用户详情
exports.getUserById = (req, res) => {
  // 好友id
  let id = req.params.id
  let token = req.get('Authorization').split(' ')[1]
  // 自己的id
  let user_id = jwt.verify(token, secretKey).id
  // 对好友的昵称备注
  server.hasNickName(user_id, id).then(nick_name => {
    // 获取详情
    server.getFriendDetail(id).then(result => {
      if (result.hasOwnProperty('register_time')) {
        result.register_time = utils.formatDate(new Date(result.register_time).getTime())
        result.nick_name = nick_name
      }
      return res.send({
        code: 200,
        message: "获取用户信息成功",
        data: result
      })
    }).catch(e => {
      return res.cc(e)
    })
  }).catch(e => {
    return res.cc(e)
  })
}